package com.xuecheng.controller;

import com.xuecheng.dto.UploadFileParamsDTO;
import com.xuecheng.model.RestResponse;
import com.xuecheng.service.MediaFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@Slf4j
@Api(value = "大文件上传接口", tags = "大文件上传接口")
@RestController
public class BigFilesController {
	
	@Resource
	private MediaFileService mediaFileService;
	
	@ApiOperation(value = "文件上传前检查文件")
	@PostMapping("/upload/checkfile")
	public RestResponse<Boolean> checkfile(
		@RequestParam("fileMd5") String fileMd5
	) {
		log.info("文件上传前检查文件，fileMd5:{}", fileMd5);
		return mediaFileService.checkFile(fileMd5);
		
	}
	
	@ApiOperation(value = "分块文件上传前的检测")
	@PostMapping("/upload/checkchunk")
	public RestResponse<Boolean> checkchunk(@RequestParam("fileMd5") String fileMd5,
	                                        @RequestParam("chunk") int chunk) {
		log.info("分块文件上传前的检测，fileMd5:{},chunk:{}", fileMd5, chunk);
		return mediaFileService.checkChunk(fileMd5, chunk);
	}
	
	@ApiOperation(value = "上传分块文件")
	@PostMapping("/upload/uploadchunk")
	public RestResponse<Boolean> uploadchunk(@RequestParam("file") MultipartFile file,
	                                         @RequestParam("fileMd5") String fileMd5,
	                                         @RequestParam("chunk") int chunk) throws Exception {
		log.info("上传分块文件，fileMd5:{},chunk:{}", fileMd5, chunk);
		return mediaFileService.uploadChunk(fileMd5, chunk, file.getBytes());
		
	}
	
	@ApiOperation(value = "合并文件")
	@PostMapping("/upload/mergechunks")
	public RestResponse<Boolean> mergechunks(@RequestParam("fileMd5") String fileMd5,
	                                         @RequestParam("fileName") String fileName,
	                                         @RequestParam("chunkTotal") int chunkTotal) {
		Long companyId = 1232141425L;
		log.info("合并文件，fileMd5:{},chunkTotal:{}", fileMd5, chunkTotal);
		UploadFileParamsDTO uploadFileParamsDTO =
			UploadFileParamsDTO.builder().filename(fileName).fileType("001002").tags("课程视频").build();
		return mediaFileService.mergechunks(companyId, fileMd5, chunkTotal, uploadFileParamsDTO);
		
	}
	
}
